import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'
import routes from './routes'
import axios from '../api/axios.config.js'
import routerJson, { queryMenuInfo } from "@/router/router-json.js"
// 使用ElementUi组件el-menu且点击同一个el-menu-item时，页面报错NavigationDuplicated
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
	return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter)

const router = new VueRouter({
	mode: 'history',
	base: process.env.BASE_URL,
	routes
})

/* 全局路由守卫 */
router.beforeEach((to, from, next) => {
	////console.log(from.path + '----->>>>' + to.path)
	////console.log('全局守卫', to, from)
	////console.log(router.options.routes)
	document.title = "车家佳"
	new Promise(function (resolve, reject) {
		//////console.log(store.getters.user_info)
		let isEmptyObject = (obj) => {
			var name;
			for (name in obj) {
				return false;
			}
			return true;
		}
		let isLogin = !isEmptyObject(store.getters.user_info);
		if (!isLogin) {
			axios.post("/admin/login/index.php?act=login&op=isLogin").then((res) => {
				if (res.code === 1) {
					store.commit("SET_USERINFO", res.data);
					resolve(true)
				} else {
					store.commit("SET_USERINFO", {});
					resolve(false)
				}
			})
		
		} else {
			resolve(true)
		}
	}).then(data => {
		//next 要在addRoutes之前执行否则页面空白
		let isLogin = data;
		if (to.path == '/sign-in') {
			//////console.log('1>>>')
			isLogin ? next('/home') : next();
		} else {
			//////console.log('2>>>')

			// 单独针对正式服 用户名（元通汽车 做跳转） 
			const userInfo = store.getters.user_info
			let isRedirect = false, redirectPath = ''
			if (userInfo.admin_id === '189' && userInfo.admin_name === '元通汽车' && to.name === 'welcome') { // 189
				isRedirect = true
				redirectPath = '/ytcars-panel/data-statistics/data-details'
			}

			isLogin ? (isRedirect ? next(redirectPath) : next()) : next('/sign-in');
		}
		// next()
		//菜单处理
		if (data) {
			let store_menus = store.getters.menus;
			if (!store_menus) {
				//在这里加载路由 addRoutes
				let user_info = store.state.user_info;
			
				let routerList = [];
				let power = {
					path: '/power-panel/user-power',
					name: 'user-power',
					component: () => import(/* webpackChunkName: "user-power" */ '@/views/home/power-panel/user-power/tab-control.vue'),
					meta: {
						tabs: [{ label: '权限编辑', name: 'power-manage', component: () => import(/* webpackChunkName: "power-manage" */ '@/views/home/power-panel/user-power/power-manage.vue') }],
						keepAlive: false
					}
				}
				axios.post("/admin/login/index.php?act=login&op=getAuth").then((res) => {
				let routerMenus = res.data;
				//路由递归函数
				let checkRouterChildren = (routeChild) => {
					let childArr = [];
					routeChild.forEach(item => {
						//item  1 没有child直接查询   2 有child  2.1 有child但是in_page=1  属于页面中  2.2 有child 但是inpage=0  属于收纳菜单中
							if (item.child && item.child[0].in_page === '0') {
								//菜单中  真假二级菜单   收纳菜单
								childArr = childArr.concat(checkRouterChildren(item.child));
							} else if (item.child && item.child[0].in_page === '1') {
								//在页面中  那么首先找到父级  然后父级.children = 子集的循环routes
								if (!routerJson[item.description]) {
									/* console.log('item.description',item,item.description)
									console.log('子路由',checkRouterChildren(item.child)) */
									childArr = childArr.concat(checkRouterChildren(item.child));
									return;
								}
								let parent = routerJson[item.description]
								if(!parent.children){
									parent.children = [];
								}
								parent.children = parent.children.concat(checkRouterChildren(item.child));
								parent.redirect = parent.children&&parent.children[0]&&parent.children[0].path;
								if (!parent.meta) {
									parent.meta = {}
								}
								let tabsa = []
								item.child.forEach(child => {
									if (!routerJson[child.description]) {
										return;
									}
									tabsa.push({ label: child.menu_name, name: routerJson[child.description].name })
								})
								parent.meta.tabs = tabsa;
								childArr.push(parent);
							} else {
								if (!routerJson[item.description] || routerJson[item.description] === "welcome") {
									return;
								}
								childArr.push(routerJson[item.description])
							}
					})
					return childArr;
				}

				//遍历生成所有路由
				routerMenus.forEach(ele => {
					if (!(ele.description === "home" || ele.description === "ytCars") || !queryMenuInfo(ele.description)) {
						return
					}
					let menuBaseRouter = queryMenuInfo(ele.description).key;
					let routeMapItemChildren = checkRouterChildren(ele.child);
					let routeMapItem = {
						path: '/' + menuBaseRouter,
						name: menuBaseRouter,
						redirect: '/home',
						component: () => import('@/views/home/home.vue'),
						children: routeMapItemChildren
					}
					routerList.push(routeMapItem)
				});

				//判断是否拥有权限
				if (user_info.admin_is_super === '1') {
					routerList[0].children.push(power)
				}
				//判断是否已经动态添加过路由
				if (!store_menus) {
					router.addRoutes(routerList)
					//添加404
					router.addRoutes([
						{
							path: '*',
							redirect: '/404'
						}
					])
					store.commit("SET_MENUS", true);
					// ---------------------------------------------------------------------------------------------------
					if (to.path === "/home/control-panel/welcome") {
						next({ path: '/home', replace: true }) // 增加此项防止因路由重复添加导致上面的next未成功,此处再执行一次next
					}
					// ---------------------------------------------------------------------------------------------------
				}
			})
			}
		}
	}).catch(err => {
		alert(err)
		axios.post("/admin/login/index.php?act=login&op=logout")
		.then(res => {
			if (res.code === 1) {
				store.commit("SET_USERINFO", {});
				next('/sign-in')
			}
		});
	})
})

export default router
